package com.freeman.cement.service.impl;

import com.freeman.cement.mapper.BjdbDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class DataCleanupServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(DataCleanupServiceImpl.class);
    private static final int MAX_RECORDS = 50000;

    @Resource
    private BjdbDao bjdbDao;

    /**
     * 定时清理bjdb表中的历史数据,只保留最新的5万条记录
     * 每天凌晨2点执行
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanupBjdbData() {
        try {
            logger.info("开始清理bjdb表历史数据...");
            
            // 删除多余的历史数据,只保留最新的5万条MAX_RECORDS
            String sql = "DELETE FROM bjdb WHERE id <= (SELECT min_id FROM (SELECT id as min_id FROM bjdb ORDER BY id DESC LIMIT " + MAX_RECORDS + ",1) t);";
            bjdbDao.cleanupHistoricalData(sql);
            
            logger.info("bjdb表历史数据清理完成");
        } catch (Exception e) {
            logger.error("清理bjdb表历史数据失败", e);
        }
    }
} 